/*
 *                    COPYRIGHT NOTICE
 *
 *           This code is copyright protected by Freedom Inc.
 *
 *              2001-2012 All Rights Are Reserved
 */
package com.freedom.oldsong.util;

import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.StrutsStatics;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.context.support.WebApplicationContextUtils;



/**
 * @author steven.wang
 *
 */
public final class CommonWebContextUtil {

	
	public static final String USER_INFO = "USER_INFO";
	
	private CommonWebContextUtil(){
		
	}
	
	/**
	 * Save a value to session
	 * 
	 * @param name the key to identify the value stored in session
	 * @param value the value to be stored in session
	 */
	public static void saveInSession(String name, Object value) {		
		Map<String, Object>	sessionMap = ServletActionContext.getContext().getSession();		
		sessionMap.put(name, value);
	}
	
	/**
	 * Clear the value stored in session
	 * 
	 * @param name
	 */
	public static void clearSession(String name) {		
		Map<String, Object>	sessionMap = ServletActionContext.getContext().getSession();		
		sessionMap.remove(name);
	}
	
	/**
	 * Get current http session
	 * 	
	 */
	public static HttpSession getHttpSession() {		
		return getHttpServletRequest().getSession(true);
	}
	
	/**
	 * Save a value to request
	 * 
	 * @param name the key to identify the value stored in request
	 * @param value the value to be stored in request
	 */
	public static void saveInRequest(String name, Object value) {		
		getHttpServletRequest().setAttribute(name, value);		
	}
	
	/**
	 * Get a value from session
	 * 
	 * @param name the key to identify the value stored in session 
	 * @return
	 */
	public static Object getFromSession(String name) {
		Map<String, Object>	sessionMap = ServletActionContext.getContext().getSession();
		return sessionMap.get(name);
	}
	
	public static String getSessionId() {	
		return getHttpServletRequest().getSession(true).getId();
	}
	/**
	 * Store a value to cookie
	 * 
	 * @param key
	 * @param value
	 */
	public static void saveCookie(String key, String value) {
		Cookie cookie = new Cookie(key, value);
		cookie.setPath("/");
		cookie.setMaxAge(999999999);
		HttpServletResponse response = getHttpServletResponse();
		response.addCookie(cookie);
	}
	
	
	
	/**
	 * Check if the current user has the privilege
	 * 
	 * @return true if the user has the privilege
	 */
	public static boolean hasPrivilege(String key) {
		if(key == null || "".equals(key.trim())) {
			return false;
		}
		Object obj = SecurityContextHolder.getContext().getAuthentication().getPrincipal();	
		for (GrantedAuthority ga : ((UserDetails) obj).getAuthorities()) {
			if(key.equalsIgnoreCase(ga.getAuthority())) {
				return true;
			}		
		}		
		return false;
	}
	
	/**
	 * Check if the current user has the privilege under this project group
	 * 
	 * @param projectGroupId
	 * @param privilege
	 */
//	public static void checkGroupPrivilege(Long projectGroupId, String privilege) {	
//		if(projectGroupId == null || !PrivilegeUtil.hasGroupPrivilege(String.valueOf(projectGroupId), privilege)) {
//			throw new RuntimeException("No privilege for this group: group = " + projectGroupId + "; privilege = " + privilege);
//		}
//	}
	
	/**
	 * Check if the current user has the privilege under this group
	 * 
	 * @param group
	 * @param privilege
	 */
//	public static void checkGroupPrivilege(String group, String privilege) {		
//		if(group == null || !PrivilegeUtil.hasGroupPrivilege(group, privilege)) {
//			throw new RuntimeException("No privilege for this group: group = " + group + "; privilege = " + privilege);
//		}		
//	}
	
	/**
	 * Check if the current user has the privilege under this group
	 * 
	 * @param group
	 * @param privilege
	 */
//	public static void checkAnyGroupPrivilege(String group, String[] currentAuthorities) {		
//		if(!PrivilegeUtil.hasAnyGroupPrivilege(group, currentAuthorities)) {
//			throw new RuntimeException("No privilege for this group: group = " + group + "; privilege = " + Arrays.deepToString(currentAuthorities));
//		}		
//	}
	/**
	 * Get value from cookie
	 * 
	 * @param key
	 * @return
	 */
	public static String getCookie(String key) {		
		Cookie cookies[] = getHttpServletRequest().getCookies();
		if (cookies == null || cookies.length == 0){
			return "";
		}
		for (int i = 0; i < cookies.length; i++) {
			String name = cookies[i].getName();
			if (name != null && key.equalsIgnoreCase(name)){
				return cookies[i].getValue();
			}
		}
		return "";
	}
	
	/**
	 * Get the current user's login name
	 * 
	 * @return login name
	 */
	public static String getLoginName() {
		Object obj = SecurityContextHolder.getContext().getAuthentication().getPrincipal();			
		if (obj instanceof UserDetails) {
			return((UserDetails)obj).getUsername();
		} else {
			return obj.toString();
		}
	}
	
	/**
	 * Get HttpServletResponse
	 * 
	 * @return HttpServletResponse
	 */
	public static HttpServletResponse getHttpServletResponse() {
		return (HttpServletResponse)ServletActionContext.getContext().get(StrutsStatics.HTTP_RESPONSE);
	}
	
	/**
	 * Get HttpServletRequest
	 * 
	 * @return HttpServletRequest
	 */
	public static HttpServletRequest getHttpServletRequest() {
		return (HttpServletRequest)ServletActionContext.getContext().get(StrutsStatics.HTTP_REQUEST);
	}
	
	@SuppressWarnings("unchecked")
	public static boolean isLegalSessionValue(String keyInSession, Long input) {
		if(input == null) {
			return false;
		}
		List<Long> values = (List<Long>)getFromSession(keyInSession);
		if(values != null && values.size() > 0) {
			for(Long value: values) {
				if(value != null && value.compareTo(input) == 0) {
					return true;
				}
			}
		}
		return false;
	}
	
	public static Object getContextBean(String beanName) {
		return WebApplicationContextUtils.getWebApplicationContext(ServletActionContext.getServletContext()).getBean(beanName);
	}
}
